from django.shortcuts import render, redirect
from . import models
from django.http import JsonResponse

# 登录 app=1 登录案件管理系统，app=2登录人员和机构管理系统
def login(request, app):
    if app == 1:
        name = '农业行政执法案件管理系统'
    elif app == 2:
        name = '农业行政执法机构队伍管理系统'
    if request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
        user = models.UserInfo.objects.filter(username=username, password=password).first()
        if not user:
            user = models.UserInfo.objects.filter(phone=username, password=password).first()
        if not user:
            user = models.UserInfo.objects.filter(sfzhm=username, password=password).first()
        if user:
            if not user.level:
                msg = '未经管理员审核通过'
                return render(request, 'login.html', locals())
            request.session["user_id"] = user.id
            if not request.POST.get("remember"):
                request.session.set_expiry(0)
            next_url = request.GET.get("next")
            # 如果有，就跳转回登陆之前的URL
            if next_url:
                return redirect(next_url)
            # 否则默认跳转到index页面
            elif app == 1:
                return redirect("/index/1/")  # 跳转到件管理系统的主页
            else:
                return redirect("/index/2/")
        else:
            msg = '用户名或密码错误'
    return render(request, 'login.html', locals())

def unlogin(request,app):
    request.session.delete()
    return redirect("/login/{0}/".format(app))

from aj import models
#返回ajax请求
def hqdw(request,sxs):
    if sxs=='河南省':
        obj = models.Organization.objects.values_list('id', 'title').filter(xingzhengquhua__sheng=sxs)
    else:
        obj=models.Organization.objects.values_list('id','title').filter(xingzhengquhua__shi=sxs)
    ret={'n':200,"data":list(obj)}
    return JsonResponse(ret)


def test1(request):
    return render(request,'test1.html')



def test2(request):
    return render(request, 'test2.html')